package org.jxy.study.rpc.uitl;

import org.jxy.study.rpc.annotation.MyResource;
import org.jxy.study.rpc.annotation.RpcClientTarget;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;

/**
 * @author : porteryao
 * @description : 描述
 * @date : 2021/3/12 10:29
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware, InitializingBean {

    static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.context = applicationContext;
    }

    public static <T> T getBeanByClass(Class<?> clazz) {
        return (T) context.getBean(clazz);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Object> beans = context.getBeansWithAnnotation(RpcClientTarget.class);
        Iterator<Object> iterator = beans.values().iterator();
        while (iterator.hasNext()) {
            Object target = iterator.next();
            Field[] fields = target.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.getAnnotationsByType(MyResource.class) != null) {
                    field.setAccessible(true);
                    try {
                        field.set(target, ProxyBeanUtil.getProxy(field.getType()));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
